<?php
	
	require_once 'Helper/Validation.php';
	
	class RegisterModel{
		
		private $dbconnection = NULL;
		private $Usertable = "users";
		
		public function __construct(DBconnection $dbconnection){
			$this->dbconnection = $dbconnection;
		}
		
		/**
		 * Lägger till en användare i databasen
		 * 
		 * @return bool om lyckats eller inte
		 */
		public function AddUser($user){
					
			$sql = "INSERT INTO $this->Usertable (email_address, username, password) VALUES (?,?,?)";			
			$stmt = $this->dbconnection->Prepare($sql);
			$stmt->bind_param("sss", $user->email_address, $user->username, $user->password);
			
			if ($stmt === FALSE) {
				return FALSE;
			}
			
			$stmt->execute();
			if ($stmt->affected_rows != 1) {					
				return FALSE;
			}
			
			$stmt->close();
			
			return TRUE;
		}
		
		/**
		 *  Validerar
		 * 	@Param User $user
		 * 	@Param InputValidate $validate
		 * 	@return InputValidate
		 */
		public function ValidateUser($user, $validate){
			
			$validate->isValidUsername($user->username);
			$validate->IsValidEmail($user->email_address);
			$validate->IsValidPassword($user->password);
					
					
			if ($this->UserExists($user->username)){
				$validate->AddError("Användarnamnet finns redan");
			}
					
			return $validate;
		}
		 
		/**
		 * @return bool om användare finns eller inte
		 */
		public function UserExists($username){
			$sql = "SELECT username FROM $this->Usertable WHERE username = ?";
			
			$stmt = $this->dbconnection->Prepare($sql);

			$stmt->bind_param("s", $username);
			
			$stmt->execute();
			
			$ret = $stmt->fetch();
			
			$stmt->close();
			
			if ($ret === TRUE) {
				return TRUE;
			}			
			return FALSE;
		}
		
		/**
		 * Tar bort användare
		 * @return bool om lyckats eller ej
		 */
		public function RemoveUser($user){
			$sql = "DELETE FROM $this->Usertable WHERE username=? AND password=?";			
			$stmt = $this->dbconnection->Prepare($sql);
			$stmt->bind_param("ss", $user->username, $user->password);
			if ($stmt === FALSE) {
				return FALSE;
			}
			$stmt->execute();
			if ($stmt->affected_rows != 1) {
				$stmt->close();
				return FALSE;
			}
			$stmt->close();
			
			return TRUE;
		}
		
		
		
	}
